package com.shelpe.services.sinbad.controller.sinbad;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.shelpe.services.sinbad.controller.dto.EffectDto;
import com.shelpe.services.sinbad.entity.jpa.Adgroup;
import com.shelpe.services.sinbad.entity.jpa.Creative;
import com.shelpe.services.sinbad.entity.jpa.Product;
import com.shelpe.services.sinbad.entity.jpa.ProductImages;
import com.shelpe.services.sinbad.entity.jpa.User;
import com.shelpe.services.sinbad.repository.jpa.AdgroupRepository;
import com.shelpe.services.sinbad.repository.jpa.CreativeRepository;
import com.shelpe.services.sinbad.repository.jpa.ProductImageRepository;
import com.shelpe.services.sinbad.repository.jpa.ProductRepository;
import com.shelpe.services.sinbad.repository.jpa.UserRepository;
import com.shelpe.services.sinbad.service.rpt.CreativeService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping(value = "/sinbadservice/v2")
@Api("创意相关的API")
@Slf4j
public class Creative2Controller {
	private static String PRODUCT_URL = "http://img.taobaocdn.com/bao/uploaded";

	@Autowired
	private AdgroupRepository adgroupRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private ProductImageRepository productImageRepository;
	@Autowired
	private CreativeRepository creativeRepository;
	@Autowired
	private CreativeService creativeService;
	@Autowired
	private ProductRepository productRepository;

	@ApiOperation(value = "创意的筛选")
	@RequestMapping(method = RequestMethod.GET, path = "/adgroups/creatives/@creative_model")
	public CreativeModel findCreativeModel(@RequestParam(name = "product_id") long productID) {
		CreativeModel retDto = new CreativeModel();

		Product product = this.productRepository.findOne(productID);
		Assert.notNull(product, "product_not_exist");
		retDto.from(product);

		User user = this.userRepository.findOne(product.getUserID());
		Assert.notNull(user, "user_not_exist");

		retDto.setCreatives(new ArrayList<CreativeUrl>());
		if (user.getUserType() == 2) {
			CreativeUrl url = new CreativeUrl();
			url.from(product);
			retDto.getCreatives().add(url);
		} else {
			List<ProductImages> images = this.productImageRepository.findByProductID(productID);
			Assert.isTrue(images != null && images.size() > 0, "images_not_exist");
			for (ProductImages image : images) {
				CreativeUrl url = new CreativeUrl();
				url.from(image);
				retDto.getCreatives().add(url);
			}
		}
		return retDto;
	}

	@ApiOperation(value = "创意的查看")
	@RequestMapping(method = RequestMethod.GET, path = "/adgroups/{adgroup_id}/creatives")
	@ResponseBody
	public CreativeDto findCreative(@PathVariable("adgroup_id") long adgroupID,
			@RequestParam(required = false, name = "days", defaultValue = "0") int days,
			@RequestParam(required = false, name = "device", defaultValue = "all") String device,
			@RequestParam(required = false, name = "start") String startDate,
			@RequestParam(required = false, name = "end") String endDate) {
		CreativeDto dto = new CreativeDto();

		Adgroup adgroup = this.adgroupRepository.findOne(adgroupID);
		Assert.notNull(adgroup, "adgroup_not_exist");
		dto.setProductID(adgroup.getProductID());
		User user = this.userRepository.findOne(adgroup.getUserID());
		Assert.notNull(user, "user_not_found");
		List<ProductImages> images = new ArrayList<ProductImages>();
		if (user.getUserType() == 2) {
			ProductImages image = new ProductImages();
			image.setUrl(adgroup.getProductUrl());
			image.setPosition(0);
			image.setImageId(0L);
			images.add(image);
		} else {
			images = this.productImageRepository.findByProductID(adgroup.getProductID());
			Assert.notNull(images, "images_not_exist");
		}

		dto.setCreativeUrls(new ArrayList<CreativeUrl>());
		for (ProductImages image : images) {
			CreativeUrl url = new CreativeUrl();
			if (image.getPosition() == 0) {
				url.setOriginal(true);
			}
			url.setPosition(image.getPosition());
			url.setUrl(image.getUrl());
			url.setUrlID(image.getImageId());
			dto.getCreativeUrls().add(url);
		}

		List<Creative> creatives = this.creativeRepository.findByAdgroupID(adgroupID);
		if (creatives == null || creatives.size() == 0) {
			dto.setCreatives(new ArrayList<CreativeTemplete>());
			return dto;
		}

		dto.setCreatives(new ArrayList<CreativeTemplete>());
		Date yesterday = DateUtils.addDays(new Date(), -1);
		endDate = DateFormatUtils.format(yesterday, "yyyy-MM-dd");
		if (days > 0) {
			startDate = DateFormatUtils.format(DateUtils.addDays(yesterday, -days + 1), "yyyy-MM-dd");
		} else {
			if (StringUtils.isBlank(startDate) && StringUtils.isBlank(endDate)) {
				startDate = DateFormatUtils.format(DateUtils.addDays(yesterday, -6), "yyyy-MM-dd");
			}
		}
		for (Creative creative : creatives) {
			CreativeTemplete templete = new CreativeTemplete();
			templete.setCreativeID(creative.getAutoID());
			templete.setTitle(creative.getTitle());
			templete.setUrl(creative.getImage());
			templete.setEffectMetric(
					this.creativeService.creativeMetric(creative.getAutoID(), device, startDate, endDate));
			dto.getCreatives().add(templete);
		}
		log.debug("finish find creatives:{}", dto);
		return dto;
	}

	@Data
	public static class CreativeModel {
		private List<CreativeUrl> creatives;
		@JsonProperty("product_name")
		private String productName;

		public void from(Product product) {
			this.productName = product.getProductName();
		}
	}

	@Data
	public static class CreativeDto {
		@JsonProperty("product_id")
		private long productID;
		@JsonProperty("creative_urls")
		private List<CreativeUrl> creativeUrls;
		private List<CreativeTemplete> creatives;
	}

	@Data
	public static class CreativeTemplete {
		@JsonProperty("creative_id")
		private long creativeID;
		private String url;
		private String title;
		@JsonProperty("effect_metric")
		private EffectDto effectMetric;
	}

	@Data
	public static class CreativeUrl {
		private int position;
		@JsonProperty("is_original")
		private boolean original;
		@JsonProperty("url_id")
		private long urlID;
		private String url;

		public void from(ProductImages image) {
			if (image.getPosition() == 0) {
				this.setOriginal(true);
			}
			this.setPosition(image.getPosition());
			if (!image.getUrl().contains(PRODUCT_URL)) {
				this.setUrl(PRODUCT_URL + image.getUrl());
			} else {
				this.setUrl(image.getUrl());
			}
			this.setUrl(image.getUrl());
			this.setUrlID(image.getImageId());
		}

		public void from(Product product) {
			if (!product.getPictureUrl().contains(PRODUCT_URL)) {
				this.url = PRODUCT_URL + product.getPictureUrl();
			} else {
				this.url = product.getPictureUrl();
			}
		}
	}
}
